import React from 'react'
import styles from './index.less'
import classNames from 'classnames'
import { CanvasContext } from '@/Context'
export default class Rotate extends React.Component {
	static contextType = CanvasContext
	// 组件旋转
	rotate = e => {
		e.stopPropagation()
		e.preventDefault()
		const cmp = this.context.getSelectedCmp()
		const { height, transform } = cmp.style
		const trans = parseInt(transform)
		const r = height / 2
		// 先计算出一个角度来构成三角
		const ang = ((trans + 90) * Math.PI) / 180
		const offsetX = -Math.cos(ang) * r
		const offsetY = -Math.sign(ang) * r
		const startX = e.pageX + offsetX
		const startY = e.pageY + offsetY
		const move = e => {
			const x = e.pageX
			const y = e.pageY
			const disX = x - startX
			const disY = y - startY
			let deg = (360 * Math.atan2(disY, disX)) / (2 * Math.PI) - 90
			deg = parseInt(deg)
			this.context.updateAssemblyCmps({ transform: deg - transform })
		}
		const up = () => {
			this.context.recordCanvasChangeHistory()
			document.removeEventListener('mousemove', move)
			document.removeEventListener('mouseup', up)
		}
		document.addEventListener('mousemove', move)
		document.addEventListener('mouseup', up)
	}
	render() {
		const { zoom, style } = this.props
		const { width, height, transform } = style

		return (
			<div
				className={classNames(styles.assetRotate, 'iconfont icon-xuanzhuan')}
				style={{
					top: height + (30 * 100) / zoom,
					left: width / 2 - 13,
					transform,
				}}
				onMouseDown={this.rotate}
			></div>
		)
	}
}
